package cn.zoujiedev.netty.core.serialization;

import com.caucho.hessian.io.Hessian2Input;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;

/**
 * @Classname HessianDecoder
 * @Description
 * @Date 2022-11-3 14:11
 * @Created by zoujie
 */
public class HessianDecoder implements ObjectDecoder{

  @Override
  public Object decode(ByteBuf in) throws Exception{

    ByteBufInputStream input = null;
    Hessian2Input hessian2Input = null;
    try {
      int objectLength = in.readInt();
      ByteBuf slice = in.slice(in.readerIndex(), objectLength);
      input = new ByteBufInputStream(slice);
      hessian2Input = new Hessian2Input(input);

      Object o = hessian2Input.readObject();
      in.readerIndex(in.readerIndex() + objectLength);

      return o;
    }finally {
      if(input != null){
        input.close();
      }

      if(hessian2Input != null){
        hessian2Input.close();
      }
    }
  }
}
